package config

import (
	"bytes"
	"crypto/aes"
)

// 扩展秘钥
func expandKey(key []byte) []byte {
	expandedKey := make([]byte, 16)
	for i := range expandedKey {
		//todo 需要改成16位 和php 算法一致
		expandedKey[i] = key[i%16]
	}
	return expandedKey
}

// Encrypt AES-128-ECB加密   用于密码加密
func Encrypt(text []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(expandKey(key))
	if err != nil {
		return nil, err
	}
	text = pad(text, aes.BlockSize)
	ciphertext := make([]byte, len(text))
	size := aes.BlockSize
	for i := 0; i < len(text); i += size {
		block.Encrypt(ciphertext[i:i+size], text[i:i+size])
	}
	return ciphertext, nil
}

// 填充数据
func pad(buf []byte, blockSize int) []byte {
	padding := blockSize - (len(buf) % blockSize)
	padtext := bytes.Repeat([]byte{0}, padding)
	return append(buf, padtext...)
}

func PadToBlockSize(data []byte) []byte {
	padNum := aes.BlockSize - (len(data) % aes.BlockSize)
	padText := bytes.Repeat([]byte{byte(padNum)}, padNum)
	return append(data, padText...)
}

type System struct {
	Id         int    `json:"id"`
	Nickname   string `orm:"column(nickname)" json:"nickname"`
	Tel        string `orm:"column(tel)" json:"tel"`
	Headimg    string `orm:"column(headimg)" json:"headimg"`
	CreateTime int    `orm:"column(create_time)" json:"create_time"`
}

// UniqueBySubElement 数组根据某列去重数据
// slice 数据
// n     某一列
func UniqueBySubElement(slice [][]string, n int) [][]string {
	m := make(map[string]bool)
	unique := [][]string{}

	for _, subSlice := range slice {
		key := subSlice[n] // 假设我们以子切片的第一个元素作为去重的依据
		if !m[key] {
			m[key] = true
			unique = append(unique, subSlice)
		}
	}

	return unique
}
